package com.pfzy.utildemo.activity.record.recording2;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.RequiresApi;

//import com.maitianshanglv.im.app.common.BaseObserver;
//import com.maitianshanglv.im.app.common.BuildConfig;
//import com.maitianshanglv.im.app.common.MyConst;
//import com.maitianshanglv.im.app.common.R;
//import com.maitianshanglv.im.app.common.api.HttpLoader;
//import com.maitianshanglv.im.app.common.bean.SuccessBean;
//import com.maitianshanglv.im.app.common.bean.TokenBean;
//import com.maitianshanglv.im.app.common.manager.AudioManager;
//import com.qiniu.android.http.ResponseInfo;
//import com.qiniu.android.storage.Configuration;
//import com.qiniu.android.storage.UpCompletionHandler;
//import com.qiniu.android.storage.UpProgressHandler;
//import com.qiniu.android.storage.UploadManager;
//import com.qiniu.android.storage.UploadOptions;

import com.pfzy.lib.config.log.MyLog;
import com.pfzy.utildemo.activity.record.sdk.AudioManager;
import com.pfzy.utildemo.utils.NotificationUtils;

public class RecordService extends Service {
    private static volatile RecordService instance;// 确保变量的可见性和禁止指令重排序优化。

    public static RecordService getInstance(Context context) {
        if (instance == null) {
            synchronized (RecordService.class) {
                if (instance == null) {
                    instance = new RecordService();
                }
            }
        }
        return instance;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(NotificationUtils.NOTIFY_ID, NotificationUtils.buildNotification(getApplicationContext()));
        AudioManager.getInstance(this).startRecord();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

//    private static String qiniuToken;
//    private static String hostUrl;
//    private static String driverId;
//    private static String orderId;
//    private static ScheduledFuture<?> mFuture;
//    private static Context mContext;
//    private static Configuration config = new Configuration.Builder().build();
//    private static UploadManager uploadManager = new UploadManager(config);
//    private static boolean isDone = false;
//    private static ScheduledFuture<?> mFutureUpload;
//
//
//    /**
//     * 关闭服务
//     */
//    public void stopService(Context context) {
//        isDone = true;
//        starUpload();
//    }
//
//    private void loadRecord(String path, String token, String url) {
//        String uuid = getUUid();
//        Long time = new Date().getTime();
//        Long timeOp = System.currentTimeMillis() / 1000;
//        String data = (DateUtils.yearMonthStamp2Date(time)).replace("-", "");
//        File file = new File(path);
//        String name = file.getName();
//        String orderId = name.substring(name.indexOf("_") + 1, name.lastIndexOf("_"));
//        String autioTime = name.substring(name.lastIndexOf("_") + 1, name.indexOf("."));
//        String keyname = MyConst.QINIU_AUDIO_FORMAT + autioTime + "/" + uuid + orderId + timeOp + ".aac";
//        Log.d(TAG, "keyname " + keyname);
//        Log.d(TAG, "name " + name);
//        if (file.length() == 0L) {
//            file.delete();
//        } else {
//            uploadManager.put(file, keyname, token, new UpCompletionHandler() {
//                @Override
//                public void complete(String key, ResponseInfo info, JSONObject response) {
//                    if (info.isOK()) {
//                        if (name.contains("_")) {
//                            String driverId = name.substring(0, name.indexOf("_"));
//                            String orderId = name.substring(name.indexOf("_") + 1, name.lastIndexOf("_"));
//                            Long autioTime = Long.parseLong(name.substring(name.lastIndexOf("_") + 1, name.indexOf("."))) / 1000;
//                            String audioUrl = url + "/" + keyname;
//                            Log.d(TAG, "complete: orderId: " + orderId + ",driverId: " + driverId + ",autioTime: " + autioTime + ",audioUrl: " + audioUrl);
//                            Observable observable = httpLoader.employAudioCreate(orderId, driverId, autioTime, audioUrl);
//                            observable.subscribe(new BaseObserver<SuccessBean>(mContext) {
//                                @Override
//                                protected void reLoad() {
//                                }
//
//                                @Override
//                                public void onNext(SuccessBean successBean) {
//                                    Log.d(TAG, "上传返回code " + successBean.getCode());
//                                    if (successBean.getCode().equals("0000")) {
//                                        Log.e(TAG, "上传返回code " + successBean.getCode());
//                                        if (file.exists()) {
//                                            Log.d(TAG, "删除文件");
//                                            file.delete();
//                                            Log.d(TAG, "isDone " + isDone);
//                                        }
//                                    }
//                                }
//                            });
//                        }
//                    }
//                }
//            }, new UploadOptions(null, null, false, new UpProgressHandler() {
//                @Override
//                public void progress(String key, double percent) {
//                }
//            }, null));
//        }
//    }
//
//    private void stopRecord() {
//        AudioManager.getInstance(mContext).endRecord();
//        File[] fs = AudioManager.getInstance(mContext).prepareRecord();
//        for (File file : fs) {
//            loadRecord(file.getPath(), qiniuToken, hostUrl);
//        }
//    }
//
//    private void startRecord() {
//        // 打断录音并重新开始录音
//        mFuture = Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() {
//            @Override
//            public void run() {
//                Log.e(TAG, "startRecord: 上传录音");
//                AudioManager.getInstance(mContext).endRecord();
//
//                long time = System.currentTimeMillis();
//                File[] fs = AudioManager.getInstance(mContext).prepareRecord();
//                int fileSize = fs.length;
//                Log.e(TAG, "startRecord: " + DateUtils.timeStamp2Date(time) + ", fileSize: " + fileSize);
//
//                if (isDone) {
//                    if (fs.length == 0) {
//                        Log.d(TAG, "run: 文件上传完成 停止服务");
//                        mFuture.cancel(false);
//
//                        Intent intent = new Intent();
//                        intent.setClass(mContext, RecordService.class);
//                        stopService(intent);
//                    } else {
//                        for (File file : fs) {
//                            loadRecord(file.getPath(), qiniuToken, hostUrl);
//                        }
//                    }
//                } else {
//                    for (File file : fs) {
//                        loadRecord(file.getPath(), qiniuToken, hostUrl);
//                    }
//                    AudioManager.getInstance(mContext).startRecord(driverId, orderId);
//                }
//            }
//        }, 12000 * 1000, 12000 * 1000, TimeUnit.MILLISECONDS);
//    }
//
//    private void starUpload() {
//        mFutureUpload = Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(new Runnable() {
//            @Override
//            public void run() {
//                Log.e(TAG, "starUpload: 上传录音");
//                AudioManager.getInstance(mContext).endRecord();
//
//                long time = System.currentTimeMillis();
//                File[] fs = AudioManager.getInstance(mContext).prepareRecord();
//                int fileSize = fs.length;
//                Log.e(TAG, "starUpload: " + DateUtils.timeStamp2Date(time) + ", fileSize: " + fileSize);
//                if (fs.length == 0) {
//                    Log.d(TAG, "run: 文件上传完成 定时停止");
//                    mFutureUpload.cancel(false);
//                    Intent intent = new Intent();
//                    intent.setClass(mContext, RecordService.class);
//                    mContext.stopService(intent);
//                } else {
////                    loadRecord(fs[0].getPath(), qiniuToken, hostUrl);
//                    for (File file : fs) {
//                        loadRecord(file.getPath(), qiniuToken, hostUrl);
//                    }
//                }
//            }
//        }, 1, 20, TimeUnit.SECONDS);
//    }
//
//    // 生成uuid
//    private String getUUid() {
//        String id = UUID.randomUUID().toString();
//        id = id.replace("-", "");
//        return id;
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        _logd("onDestroy ");
        stopForeground(true);
    }

    private void _logd(String msg) {
        MyLog.logd("录音服务 " + msg);
    }
}